<?php

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-05-12
 * Time: 10:22:49
 * Info:
 */

namespace app\common\service;

use think\facade\Db;

class MenuService
{

    public function getMenuTree()
    {
        return $this->buildMenuChild(0, $this->getMenuData());
    }

    private function buildMenuChild($pid, $menuList, $authCheck = true)
    {
        $uid      = cmf_get_admin_id();
        $treeList = [];
        foreach ($menuList as $key => $v) {
            $vNode = trim($v['node']);
            $check = empty($vNode) ? true : check_auth($vNode);
            if ($pid == $v['pid'] && $check) {
                $node  = $v;
                $child = $this->buildMenuChild($v['id'], $menuList, $authCheck);
                if ($v['pid'] == 0 && empty($child)) {
                    unset($v);
                }
                if ( ! empty($child)) {
                    $node['children'] = $child;
                }
                if ( ! empty($vNode) || ! empty($child)) {
                    $treeList[] = $node;
                }
            }
        }

        return $treeList;
    }

    protected function getMenuData()
    {
        $menuData = Db::name('auth_menu')->field('id,pid,title,icon,node,open_type,type')->where("delete_time",
            0)->where([
            ['is_menu', '=', '1'],
            ['pid', '<>', 99999999],
        ])->where('status', 1)->order([
            'sort' => 'asc',
            'id'   => 'asc',
        ])->select()->toArray();
        foreach ($menuData as $key => $v) {
            $menuData[$key]['icon'] = "layui-icon ".$v['icon'];
            $menuData[$key]['href'] = $v['node'];
        }

        return $menuData;
    }
}
